<?php
/**
 * Created by PhpStorm.
 * User: cuipengyu
 * Date: 2019/3/23
 * Time: 0:26
 */
ignore_user_abort(); // 后台运行
set_time_limit(0); // 取消脚本运行时间的超时上限

header ( "Content-type:text/html;charset=utf-8" );

require_once('Lib/Common/common.php');

$logpath =  'Runtime/Logs/runsvr3.html';
$file_last_runapis_time =  'Runtime/Logs/runapis3';
$file_config = 'Runtime/Conf/config.php';

$mustStop = false;
$longSleep = 300;
$shortSleep = 120;
$minSleep =10;
$runversion = '1.05';
$indexHotkeywords = 0;


if(!file_exists($file_last_runapis_time)) {
    $f2=fopen($file_last_runapis_time, "w");
    fclose($f2);
}else {
    $f1 = fopen($file_last_runapis_time, 'r');
    $lasttime = fread($f1, filesize($file_last_runapis_time));
    fclose($f1);
    // 如果未超时30分钟，则不允许执行
    $lastsecond = time() - $lasttime;
    if ($lasttime > 0 &&  $lastsecond < 30*60 ) {
        echo ('已经被调用且正在执行,上次运行于 '.($lastsecond/60).'分钟前，本次请求被取消。');
        return;
    }
}

$conn = conndb();

try{

    while(true) {

        if(!canrun()){
            break;
        }


        $sql = 'select vod_id,vod_name,vod_douban_id,vod_content from ff_vod where vod_douban_id is not null and vod_douban_id != \'\' and vod_status=1 order by vod_addtime limit 1' ;
        $arr = querydb($conn, $sql);

        if(!$arr&& count($arr)==0){
            dolog('no vod rows');
            break;
        }

        $arr3 = $arr[0];

        $conf = @include($file_config);
        $proxy = $conf['proxy'];
        if(!$proxy&&$proxy!='') {
            $arrProxy = explode(":", $proxy);
        }else{
            $arrProxy=['https','142.93.44.189','3128'];
        }

        $url1 = 'https://movie.douban.com/subject/'.$arr3['vod_douban_id'].'/';
        $html1 = ff_file_get_contents($url1,110,'','',$arrProxy[0],$arrProxy[1], $arrProxy[2]);

        // 如果读取内容异常
        if (!$html1||  strpos($html1, '到有异常请求从你的 IP 发出') > 0 || strpos($html1, '"url": "/subject/'.$arr3['vod_douban_id'].'/",') === false  ) {
            $html1=$arr3['vod_content'];
        }else {

            // 从豆瓣获取了最新的简介，则继续
            $hassummary = preg_match("#<span class=\"all hidden\">([\s\S]+?)</span>#mi", $html1, $mc1);

            if ($hassummary && $mc1[1]) {
                $summary = trim($mc1[1]).'<br><br>';
            }else{
                $hassummary = preg_match("#<span property=\"v:summary\" class=\"\">([\s\S]+?)</span>#mi", $html1, $mc1);
                if ($hassummary && $mc1[1]) {
                    $summary = trim($mc1[1]).'<br><br>';
                }else{
                    $summary='';
                }
            }

            // 解析第一篇评论的Id
            $hasShortContent = preg_match('#id=\"review_(\d+?)_short\"#si', $html1, $mc2);
            if ($hasShortContent && $mc2) {
                $doubanShortContentId = trim($mc2[1]);

                // 休眠若干秒钟
                sleep($minSleep);
                $url2 = 'https://movie.douban.com/j/review/' . $doubanShortContentId . '/full';
                $html2 = ff_file_get_contents($url2, 110, '', '', $arrProxy[0],$arrProxy[1], $arrProxy[2]);
                $arrShortContent = json_decode($html2, false);

                $shortContent = $arrShortContent->html;

            }

            $html1 =$summary . $shortContent;

        }

//        $info=['word'=>$html1 ] ;
//        $url='http://wordrobot.pingbuwang.com/convert';
//
//        $context = stream_context_create(array(
//            'http' => array('method' => 'POST','header' => 'Content-type:application/x-www-form-urlencoded','content' => http_build_query($info),'timeout' => 150 )
//        ));
//
//        try {
//            $result = file_get_contents($url, false, $context);
//        }catch (Exception  $err){
//            $result = $html1;
//        }

        $result = $html1;


        // 向文章中插入关键字。
        $result = addKeyword($result);
        $result = str_replace('</ ','</',$result);

        $sql2 = 'update ff_vod set vod_content =?,vod_addtime='.time().'  where vod_id = '.$arr3['vod_id'];
        $stmt = $conn->prepare($sql2);
        $stmt->bind_param('s',$content);
        $content = $result;
        $stmt->execute();

        dolog("重新处理了电影 (".$arr3['vod_id'].")".$arr3['vod_name']."的简介。");
        sleep($longSleep);
        //break;
    }

    dolog('进程已经结束');

}finally{
    unlink($file_last_runapis_time);
    $conn.close();
}

function conndb(){
    global $file_config;
    $config = @include($file_config);
    $dbhost = $config['db_host'];
    $dbuser = $config['db_user'];
    $dbpwd = $config['db_pwd'];
    $dbname = $config['db_name'];
    $dbport = $config['db_port'];

    $conn = new mysqli($dbhost, $dbuser, $dbpwd, $dbname,$dbport);
    if ($conn->connect_error) {
        die("连接失败: " . $conn->connect_error);
    }

    $conn->query("SET NAMES utf8");
    return $conn;
}

function querydb($conn,$sql){
    try {
        if (!$conn || $conn->connect_error) {
            die("连接失败: " . $conn->connect_error);
        }

        $arr4 = array();
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            // 输出数据
            while ($row = $result->fetch_assoc()) {
                $arr4[] = $row;
            }
            return $arr4;
        } else {
            return null;
        }

    }catch (Exception $err){
        dolog($err);
    }
    return null;

}

function canrun(){
    global $file_last_runapis_time;
    global $mustStop;

    if($mustStop){
       return false;
    }

    // 停止运行
    if(!file_exists($file_last_runapis_time)){
        dolog ($file_last_runapis_time.'被删除，执行停止<br>');
        $mustStop=true;
        return false;
    }

    record_last_run();

    return true;
}

// 记录最后一次运行的时间
function record_last_run(){
    global $file_last_runapis_time;
    $f2=fopen($file_last_runapis_time, "w");
    fwrite($f2,time() );
    fclose($f2);
}

function dolog($msg){
    global $runversion;
    global $logpath;

    if(filesize($logpath)> 1500){
       unlink($logpath);
    }

    if(!$msg){
        $msg='empty msg!!!';
    }
    $msg = $runversion.' :: '.date('Y-m-d H:i:s',time()).'::'. charsetToGBK($msg).'<br>';
    file_put_contents($logpath, $msg ,FILE_APPEND);
}

function charsetToGBK($mixed)
{
    try {
        if (is_array($mixed)) {
            foreach ($mixed as $k => $v) {
                if (is_array($v)) {
                    $mixed[$k] = charsetToGBK($v);
                } else {
                    $encode = mb_detect_encoding($v, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
                    if ($encode == 'UTF-8') {
                        $mixed[$k] = iconv($encode, 'GBK', $v);
                    }
                }
            }
        } else {
            $encode = mb_detect_encoding($mixed, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
            if ($encode == 'UTF-8') {
                $mixed = iconv($encode, 'GBK', $mixed);
            }
        }
    }catch (Exception $err){
        return 'to gbk is error';
    }
    return $mixed;
}

/**
 * @param $content向文章中插入关键字
 * 插入在第一个句号之后；
 */
function addKeyword($content){
    global $indexHotkeywords;
    $arrKeywords = getHotKeywords();

    $index1 = ($indexHotkeywords++)% sizeof($arrKeywords);
    $pos1 = strpos($content,'，');
    $strKeywords1 = $arrKeywords[$index1];
    $aKeywords1 = _getAbyHotKeyword($strKeywords1);
    if($pos1 === false || $pos1 ===0 ) {
        $pos1 = 0;
    }else{
        $aKeywords1=$aKeywords1;
    }
    $content1 =substr_replace($content,$aKeywords1,$pos1,0);

    $index2 = ($indexHotkeywords++)% sizeof($arrKeywords);
    $pos2 = strpos($content1,'，',$pos1+strlen($aKeywords1)+1 );
    $strKeywords2 = $arrKeywords[$index2];
    $aKeywords2 = _getAbyHotKeyword($strKeywords2);
    if(!$pos2 ) {
        return $content1;
    }
    $aKeywords2=$aKeywords2;
    $content2 =substr_replace($content1,$aKeywords2,$pos2,0);

    return $content2;
}

function getHotKeywords(){
    global $file_config;

    $config = @include($file_config);
    $strHotKeywords = $config['hot_keywords'];
    $arrHotKeywords = explode(PHP_EOL,$strHotKeywords);
    return $arrHotKeywords;
}

function _getAbyHotKeyword($hotKeyword){
    if(!$hotKeyword){
        return '';
    }
    $arr = explode('$',$hotKeyword);
    if(!$arr||sizeof($arr)<2){
        return '';
    }
    return "<a href='{$arr[1]}' class='ff_hotkeyword'>{$arr[0]}</a>";
}